<template>
  <div class="coach-home">
    <el-row :gutter="20">
      <!-- 左侧栏 -->
      <el-col :span="16">
        <!-- 教学统计 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-card class="stats-card primary">
              <div class="stats-content">
                <div class="stats-icon">👥</div>
                <div class="stats-info">
                  <div class="stats-number">{{ currentStudents }}</div>
                  <div class="stats-label">当前学员</div>
                </div>
              </div>
            </el-card>
          </el-col>

          <el-col :span="8">
            <el-card class="stats-card success">
              <div class="stats-content">
                <div class="stats-icon">📅</div>
                <div class="stats-info">
                  <div class="stats-number">{{ totalAppointments }}</div>
                  <div class="stats-label">总预约数</div>
                </div>
              </div>
            </el-card>
          </el-col>

          <el-col :span="8">
            <el-card class="stats-card warning">
              <div class="stats-content">
                <div class="stats-icon">✅</div>
                <div class="stats-info">
                  <div class="stats-number">{{ completedAppointments }}</div>
                  <div class="stats-label">已完成</div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 近期预约 -->
        <el-card class="schedule-card">
          <template #header>
            <div class="card-header">
              <span>近期预约</span>
              <el-button type="primary" size="small" @click="goToSchedule">
                查看全部
              </el-button>
            </div>
          </template>
          <el-table :data="recentSchedule" style="width: 100%" height="300">
            <el-table-column prop="date" label="日期" width="100" />
            <el-table-column prop="time" label="时间" width="100" />
            <el-table-column prop="student" label="学员" />
            <el-table-column prop="program" label="项目" />
            <el-table-column prop="status" label="状态" width="80">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <!-- 学员进度 -->
        <el-card class="students-progress">
          <template #header>
            <div class="card-header">
              <span>学员进度排行</span>
              <el-button type="primary" size="small" @click="goToStudents">
                查看全部学员
              </el-button>
            </div>
          </template>
          <div class="progress-container">
            <div v-for="(student, index) in studentProgress" :key="index" class="student-progress-item">
              <div class="student-info">
                <div class="student-name">{{ student.name }}</div>
                <div class="student-license">{{ student.licenseType }}</div>
              </div>
              <div class="progress-info">
                <el-progress :percentage="student.progress" :stroke-width="10" />
                <div class="progress-text">{{ student.completed }}/{{ student.total }} 课时</div>
              </div>
            </div>
          </div>
        </el-card>

      </el-col>

      <!-- 右侧栏 -->
      <el-col :span="8">
        <!-- 个人信息 -->
        <el-card class="profile-card">
          <template #header>
            <div class="card-header">
              <span>教练信息</span>
            </div>
          </template>
          <div class="profile-content">
            <div class="avatar-container">
              <div class="avatar">👨‍🏫</div>
            </div>
            <div class="profile-details">
              <div class="profile-item">
                <label>姓名:</label>
                <span>{{ coachInfo.name }}</span>
              </div>
              <div class="profile-item">
                <label>工号:</label>
                <span>{{ coachInfo.employeeId }}</span>
              </div>
              <div class="profile-item">
                <label>擅长方向:</label>
                <span>{{ coachInfo.specialization }}</span>
              </div>
              <div class="profile-item">
                <label>入职时间:</label>
                <span>{{ coachInfo.hireDate }}</span>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 最新公告 -->
        <el-card class="announcements-card">
          <template #header>
            <div class="card-header">
              <span>最新公告</span>
              <el-button type="primary" size="small" @click="goToAnnouncements">
                查看全部
              </el-button>
            </div>
          </template>
          <div class="announcements-list">
            <div
              v-for="(announcement, index) in latestAnnouncements"
              :key="index"
              class="announcement-item"
              @click="viewAnnouncement(announcement)"
            >
              <h4 class="announcement-title">{{ announcement.title }}</h4>
              <p class="announcement-content">{{ announcement.content }}</p>
              <div class="announcement-time">{{ announcement.time }}</div>
            </div>
          </div>
        </el-card>

        <!-- 快捷操作 -->
        <el-card class="quick-actions">
          <template #header>
            <div class="card-header">
              <span>快捷操作</span>
            </div>
          </template>
          <div class="actions-grid">
            <div class="action-item" @click="goToSchedule">
              <div class="action-icon">📅</div>
              <div class="action-label">我的预约</div>
            </div>
            <div class="action-item" @click="goToStudents">
              <div class="action-icon">👥</div>
              <div class="action-label">学员管理</div>
            </div>
            <div class="action-item" @click="goToFeedback">
              <div class="action-icon">💬</div>
              <div class="action-label">学员反馈</div>
            </div>
            <div class="action-item" @click="goToProfile">
              <div class="action-icon">👤</div>
              <div class="action-label">个人资料</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 公告详情对话框 -->
    <el-dialog v-model="dialogVisible" title="公告详情" width="50%">
      <div v-if="selectedAnnouncement">
        <h3>{{ selectedAnnouncement.title }}</h3>
        <p>{{ selectedAnnouncement.content }}</p>
        <div class="dialog-footer">
          <span class="announcement-time">{{ selectedAnnouncement.time }}</span>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, computed, onMounted} from 'vue'
import {useRouter} from 'vue-router'
import requestUtil from '@/util/request.js'
import {ElMessage, ElDialog} from 'element-plus'

const router = useRouter()

// 教学统计数据
const currentStudents = ref(0)
const totalAppointments = ref(0)
const completedAppointments = ref(0)

// 教练信息
const coachInfo = ref({
  name: '未加载',
  employeeId: '未加载',
  licenseType: '未加载',
  joinDate: '未加载'
})

// 近期安排数据
const allSchedule = ref([])

// 学员进度数据
const studentProgress = ref([])

// 过滤后的近期预约（显示所有非取消状态的预约）
const recentSchedule = computed(() => {
  return allSchedule.value.filter(item => item.status !== '已取消').slice(0, 5)
})


// 最新公告数据
const latestAnnouncements = ref([])

// 公告对话框
const dialogVisible = ref(false)
const selectedAnnouncement = ref(null)

// 获取教练信息和教学统计
const fetchCoachInfo = async () => {
  try {
    // 从localStorage获取用户ID
    const userId = localStorage.getItem('user_id')
    if (!userId) {
      ElMessage.error('用户未登录或会话已过期')
      return
    }

    // 通过userId获取教练id
    const coachResponse = await requestUtil.get(`/coach/msg/userId/${userId}`)
    const coachData = coachResponse.data.data
    const coachId = coachData.coach_id
    // 更新教练信息
    coachInfo.value = {
      name: coachData.fullname || '未设置',
      employeeId: coachData.license_number || '未设置',
      specialization: coachData.specialization || '未设置',
      hireDate: coachData.hire_date || '未设置'
    }

    // 获取系统的学员数量
    let studentsCount = 0
    try {
      const studentsResponse = await requestUtil.get(`/student/msg`)
      studentsCount = studentsResponse.data.total || 0
    } catch (error) {
      console.warn('获取学员数量失败:', error)
    }

    // 获取教练预约数量
    let totalApps = 0
    let completedApps = 0
    try {
      const appointmentsResponse = await requestUtil.get(`/appointment/msg/coach/${userId}`)
      if (appointmentsResponse.data && appointmentsResponse.data.data) {
        const appointments = appointmentsResponse.data.data
        // console.log('预约信息:', appointments)
        totalApps = appointments.total || 0
        // console.log('预约数量:', totalApps)
        // 使用appointments.data来过滤已完成的预约
        if (appointments.data && Array.isArray(appointments.data)) {
          completedApps = appointments.data.filter(app => app.status === 'COMPLETED').length
        }
      }
    } catch (error) {
      console.warn('获取预约信息失败:', error)
    }

    // 更新数据
    currentStudents.value = studentsCount
    totalAppointments.value = totalApps
    completedAppointments.value = completedApps
  } catch (error) {
    console.error('获取教练信息失败:', error)
    ElMessage.error('获取教练信息失败: ' + (error.message || '未知错误'))
  }
}

// 获取近期预约信息
const fetchRecentSchedule = async () => {
  try {
    // 从localStorage获取用户ID
    const userId = localStorage.getItem('user_id')
    if (!userId) {
      ElMessage.error('用户未登录或会话已过期')
      return
    }

    // 获取教练的预约信息
    const response = await requestUtil.get(`/appointment/msg/coach/${userId}`)
    // console.log('完整响应数据:', response.data.data.list)

    // 处理预约数据
    if (response.data && response.data.data && response.data.data.list) {
      const schedule = response.data.data.list  // 真正的数组在data.data.list中
      // console.log('预约数组:', schedule)
      // console.log('是否为数组:', Array.isArray(schedule))

      if (Array.isArray(schedule)) {
        allSchedule.value = schedule.map(item => ({
          id: item.appointment_id,
          date: item.appointment_date,
          time: formatTimeRange(item.start_time, item.end_time),
          student: item.student?.fullname || '未知学员',
          program: item.program?.name || '未知项目',
          status: getStatusText(item.status)  // 确保调用getStatusText函数
        }))
        // console.log('处理后的预约数据:', allSchedule.value)
      } else {
        allSchedule.value = []
      }
    } else {
      allSchedule.value = []
    }
  } catch (error) {
    console.error('获取预约信息失败:', error)
    ElMessage.error('获取预约信息失败: ' + (error.message || '未知错误'))
    allSchedule.value = []
  }
}





// 获取学员进度信息
const fetchStudentProgress = async () => {
  try {
    // 从localStorage获取用户ID
    const userId = localStorage.getItem('user_id')
    if (!userId) {
      ElMessage.error('用户未登录或会话已过期')
      return
    }

    // 获取所有学员
    const studentsResponse = await requestUtil.get('/student/msg')
    const students = studentsResponse.data.data || []
    console.log('所有学员:', students)

    // 获取每个学员的进度信息
    const progressData = []
    for (const student of students) { // 获取所有学员的进度
      try {
        // 获取学员已完成的训练项目数量
        const allTrainingsResponse = await requestUtil.get(`/student_training/trainings/user/${student.user_id_id}`)
        let allTrainings = 0

        // 检查返回的数据结构
        if (allTrainingsResponse.data && allTrainingsResponse.data.data) {
          if (Array.isArray(allTrainingsResponse.data.data)) {
            allTrainings = allTrainingsResponse.data.data
          } else if (allTrainingsResponse.data.data.list && Array.isArray(allTrainingsResponse.data.data.list)) {
            allTrainings = allTrainingsResponse.data.data.list
          }
        }
         // 从所有训练记录中筛选出状态为"已完成"的记录
        const completedTrainings = allTrainings.filter(training => {
          // 根据训练记录的状态字段判断是否已完成
          const status = training.status?.toUpperCase()
          return status === 'COMPLETED' || status === '已完成'
        }).length

        console.log(`${student.fullname} 总训练记录:`, allTrainings.length)
        console.log(`${student.fullname} 已完成训练记录:`, completedTrainings)



        // 获取总的训练项目数量
        const totalResponse = await requestUtil.get('/program/msg')
        const totalPrograms = totalResponse.data.total || 0
        console.log(`${student.fullname} totalPrograms:`, totalPrograms)

        // 计算进度百分比
        const progressPercentage = totalPrograms > 0 ? Math.round((completedTrainings / totalPrograms) * 100) : 0

        progressData.push({
          name: student.fullname || '未知学员',
          licenseType: student.license_type || '未设置',
          progress: progressPercentage,
          completed: completedTrainings,
          total: totalPrograms
        })
      } catch (error) {
        console.warn(`获取学员 ${student.fullname} 进度信息失败:`, error)
      }
    }

    // 按进度百分比排序，取前5个进度最高的学员
    progressData.sort((a, b) => b.progress - a.progress)
    studentProgress.value = progressData.slice(0, 5)

    console.log('排序后的学员进度:', progressData)
    console.log('前5名学员进度:', studentProgress.value)
  } catch (error) {
    console.error('获取学员进度信息失败:', error)
    ElMessage.error('获取学员进度信息失败: ' + (error.message || '未知错误'))
  }
}

// 获取最新公告
const fetchLatestAnnouncements = async () => {
  try {
    // 获取最新的5条公告
    const response = await requestUtil.get('/announcement/msg', {
      params: {
        page: 1,
        page_size: 5,
        is_active: true
      }
    })

    // 处理公告数据
    const announcements = response.data.data?.list || []
    latestAnnouncements.value = announcements.map(announcement => ({
      id: announcement.announcement_id,
      title: announcement.title,
      content: announcement.content?.length > 50 ?
          announcement.content.substring(0, 50) + '...' :
          announcement.content,
      time: announcement.create_at?.substring(0, 10) || ''
    }))
  } catch (error) {
    console.error('获取公告信息失败:', error)
    ElMessage.error('获取公告信息失败: ' + (error.message || '未知错误'))
  }
}

// 格式化时间范围
const formatTimeRange = (startTime, endTime) => {
  try {
    // 处理时间格式 "HH:MM:SS"，只需要 "HH:MM"
    const formatTime = (timeString) => {
      if (!timeString || typeof timeString !== 'string') {
        return '--:--'
      }

      // 分割时间字符串并取前两部分（小时和分钟）
      const parts = timeString.split(':')
      if (parts.length >= 2) {
        return `${parts[0]}:${parts[1]}`
      }
      return '--:--'
    }

    return `${formatTime(startTime)}-${formatTime(endTime)}`
  } catch (error) {
    console.error('格式化时间出错:', error, {startTime, endTime})
    return '--:--'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  try {
    const statusValue = status?.toUpperCase()
    switch (statusValue) {
      case 'CONFIRMED':
        return '已确认'
      case 'PENDING':
        return '待确认'
      case 'COMPLETED':
        return '已完成'
      case 'CANCELLED':
        return '已取消'
      default:
        return status || '未知状态'
    }
  } catch (error) {
    console.error('获取状态文本出错:', error, {status})
    return '未知状态'
  }
}

const getStatusType = (status) => {
  switch (status) {
    case '已确认':
      return 'success'
    case '待确认':
      return 'warning'
    case '已完成':
      return 'primary'
    case '已取消':
      return 'danger'
    default:
      return 'info'
  }
}

const goToSchedule = () => {
  router.push('/coach/coachAppointment')
}

const goToAnnouncements = () => {
  router.push('/coach/coachAnnouncement')
}

const goToStudents = () => {
  router.push('/coach/coachStudent')
}

const goToFeedback = () => {
  router.push('/coach/coachFeedback')
}

const goToProfile = () => {
  router.push('/coach/coachProfile')
}

const viewAnnouncement = (announcement) => {
  selectedAnnouncement.value = announcement
  dialogVisible.value = true
}

// 组件挂载时获取所有数据
onMounted(() => {
  fetchCoachInfo()
  fetchRecentSchedule()
  fetchStudentProgress()
  fetchLatestAnnouncements()
})
</script>

<style scoped>
.coach-home {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 100px);
}

/* 统计卡片样式 */
.stats-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s, box-shadow 0.3s;
}

.stats-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.stats-card.primary {
  background: linear-gradient(135deg, #409eff, #64b5f6);
  color: white;
}

.stats-card.success {
  background: linear-gradient(135deg, #67c23a, #95d475);
  color: white;
}

.stats-card.warning {
  background: linear-gradient(135deg, #e6a23c, #f3d19e);
  color: white;
}

.stats-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.stats-icon {
  font-size: 32px;
  margin-right: 15px;
}

.stats-info .stats-number {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stats-info .stats-label {
  font-size: 14px;
  opacity: 0.9;
}

/* 预约卡片 */
.schedule-card, .students-progress {
  margin-top: 20px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

/* 学员进度 */
.progress-container {
  padding: 10px 0;
}

.student-progress-item {
  padding: 15px 0;
  border-bottom: 1px solid #eee;
}

.student-progress-item:last-child {
  border-bottom: none;
}

.student-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.student-name {
  font-weight: bold;
}

.student-license {
  color: #999;
  font-size: 12px;
}

.progress-info {
  display: flex;
  align-items: center;
}

.progress-text {
  margin-left: 10px;
  font-size: 12px;
  color: #666;
  white-space: nowrap;
}

/* 右侧栏卡片 */
.profile-card, .announcements-card, .quick-actions {
  margin-bottom: 20px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

/* 教练信息 */
.profile-content {
  text-align: center;
}

.avatar-container {
  margin-bottom: 15px;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background: linear-gradient(135deg, #409eff, #64b5f6);
  display: inline-flex;
  align-items: center;
  justify-content: center;
  font-size: 40px;
  color: white;
}

.profile-details {
  text-align: left;
}

.profile-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #eee;
}

.profile-item:last-child {
  border-bottom: none;
}

.profile-item label {
  font-weight: bold;
  color: #666;
}

/* 公告列表 */
.announcements-list {
  max-height: 300px;
  overflow-y: auto;
}

.announcement-item {
  padding: 12px 0;
  border-bottom: 1px solid #eee;
  cursor: pointer;
  transition: background-color 0.3s;
}

.announcement-item:hover {
  background-color: #f9f9f9;
}

.announcement-item:last-child {
  border-bottom: none;
}

.announcement-title {
  margin: 0 0 5px 0;
  font-size: 16px;
  color: #333;
}

.announcement-content {
  margin: 5px 0;
  font-size: 14px;
  color: #666;
  line-height: 1.4;
}

.announcement-time {
  font-size: 12px;
  color: #999;
}

/* 快捷操作 */
.actions-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.action-item {
  text-align: center;
  padding: 15px;
  border-radius: 8px;
  background: #f5f7fa;
  cursor: pointer;
  transition: all 0.3s;
}

.action-item:hover {
  background: #409eff;
  color: white;
  transform: translateY(-3px);
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.3);
}

.action-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.action-label {
  font-size: 14px;
}

/* 卡片头部 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 对话框 */
.dialog-footer {
  margin-top: 20px;
  text-align: right;
}

/* 滚动条样式 */
.announcements-list::-webkit-scrollbar {
  width: 6px;
}

.announcements-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.announcements-list::-webkit-scrollbar-thumb {
  background: #c0c0c0;
  border-radius: 3px;
}

.announcements-list::-webkit-scrollbar-thumb:hover {
  background: #a0a0a0;
}
</style>
